package com.elite.groovy.callback

import cn.com.elite.PropertiesUtil
import cn.com.kh.HttpClientProxy
import com.elite.groovy.util.EliteBean
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.apache.http.HttpEntity
import org.apache.http.HttpHost
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

class autoQnFirstPreCallLoss implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(autoQnFirstPreCallLoss.class);
	@Override
	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
		try {
			long time1=System.currentTimeMillis();
			def id=UUID.randomUUID().toString();
			//上午12点前首拨有接通，不加入首拨呼损任务 查首拨呼损数据：从历史表中查7天内类型为首拨且首拨已经推送成功的数据，从其中找到录音表中没有通话记录的数据（电话未转接到坐席不会有录音记录）按保险到期日倒序排列，将这种数据插入临时表数据类型标记为send_type=2
			def seleteSQL2="insert into list_push_temporary(id,customer_guid,customer_name, mobile,  tel_1, atel_1,atel_2,atel_3, atel_4, createddate, createdby, in_enddate, custlist, activity_name, is_push,send_type,objective_guid) select sys_guid(), c.customer_guid, c2.customername, c2.mobile,  c2.tel_1,  c2.atel_1, c2.atel_2, c2.atel_3, c2.atel_4, sysdate,  'SELITE',  c.in_enddate,  c2.stringfield1,l.activity_name,  '0', '2',         l.objective_guid from List_Push_history l left join elitetask e on l.objective_guid=e.objective_guid   left join customer c on l.customer_guid = c.customer_guid left join customer c2 on c.parent_guid = c2.customer_guid  where l.is_flag = '0' and l.send_type = '1'  and (l.in_enddate - trunc(sysdate)) > 7 and trunc(l.createddate) = trunc(sysdate) and e.objective_guid is not null   and l.customer_guid not in  (select l.customer_guid  from List_Push_history l  left join event t  on l.customer_guid = t.customer_guid  where l.is_flag = '0' and l.send_type = '1' and (t.callestablished = '1' or t.customer_guid is not null) and t.callstarttime >= trunc(sysdate) and t.callstarttime < trunc(sysdate) + 1   and (l.in_enddate - trunc(sysdate)) > 7)";
			int row6=eliteBean.update(seleteSQL2,"dataSource");
			log.debug("首拨呼损加入临时表数量:"+row6);

			//查询规则表配置，当日是否为节假日
			def seleteSQL3="select case when count(*) > 0 then '1'  else '0' end con from c_freedate where freedate = sysdate";
			def result1=eliteBean.chaxun_sql(seleteSQL3, "dataSource");
			def queryMap2=result1[0];
			def holiyday = queryMap2.get("CON");


			PropertiesUtil cfg = new PropertiesUtil();
			def Te_entId = cfg.readValue("QingNiu.EntId");
			String proxyIp = cfg.readValue("QingNiu.ProxyIP");
			int proxyPort=0;
			if(cfg.readValue("QingNiu.ProxyPort")!=null&&cfg.readValue("QingNiu.ProxyPort")!="") {
				proxyPort = cfg.readValue("QingNiu.ProxyPort").toInteger();
			}

			def selectSql4="select webserviceurl from sysc_interface  where webtype='QN_MDDR'";
			def queryList1=eliteBean.chaxun_sql(selectSql4, "dataSource");
			def queryMap1=queryList1[0];
			def httpURL=queryMap1.get("WEBSERVICEURL");
			log.debug("青牛地址:"+httpURL);

			log.debug("推送首拨呼损总数:"+row6);
			int sendNum=2700; //每批数据分批推送条数
			int con = Math.ceil(row6/sendNum);
			for(int q=1;q<=con;q++) {
				def updateSQL1="update list_push_temporary set Is_push='1' where Is_push='0' and send_type='2' and rownum<='"+sendNum+"'";
				int row4=eliteBean.update(updateSQL1,"dataSource");
				//查询出所有标记好的待下发的首拨呼损数据
				String sqls = "select l.customer_guid custId,"+Te_entId+" ENTID,l.activity_name CALLLISTNAME,l.customer_guid recordKey,l.mobile,l.tel_1,l.atel_1,l.atel_2,l.atel_3,l.atel_4,l.objective_guid from list_push_temporary l left join elitetask e on l.objective_guid=e.objective_guid where l.Is_push = '1' and l.send_type = 2  and e.objective_guid is not null order by in_enddate asc"
				def resultlist2= eliteBean.chaxun_sql(sqls.toString(), "dataSource");

				JSONArray jsonArray2=JSONArray.fromObject(resultlist2);
				int ListNum2 = jsonArray2.size();
				JSONArray arr = new JSONArray();
				JSONObject obj = new JSONObject();
				//JSONObject dataObject= null;
				for(int j=0;j<ListNum2;j++) {
					JSONObject dataObject = jsonArray2.getJSONObject(j);
					log.debug(dataObject.toString());
					def cust_id=GetJV(dataObject, "CUSTID");
					def entId=GetJV(dataObject, "ENTID");
					def activity_id=GetJV(dataObject, "CALLLISTNAME");
					def recordKey=GetJV(dataObject, "RECORDKEY");
					def objectiveGuid = GetJV(dataObject, "OBJECTIVE_GUID");
					if(objectiveGuid==null || objectiveGuid=="") {
						continue;
					}
					JSONObject phoneNumbers = new JSONObject();
					phoneNumbers.put("phoneNumber1", GetJV(dataObject, "MOBILE"));
					phoneNumbers.put("phoneNumber2", GetJV(dataObject, "TEL_1"));
					phoneNumbers.put("phoneNumber3", GetJV(dataObject, "ATEL_1"));
					phoneNumbers.put("phoneNumber4", GetJV(dataObject, "ATEL_2"));
					phoneNumbers.put("phoneNumber5", GetJV(dataObject, "ATEL_3"));
					phoneNumbers.put("phoneNumber6", GetJV(dataObject, "ATEL_4"));
					obj.put("custId", cust_id+","+objectiveGuid);
					obj.put("entId", entId);
					obj.put("callListName", activity_id);
					obj.put("recordKey", recordKey);
					obj.put("phoneNumbers", phoneNumbers);
					obj.put("exData7",id);
					obj.put("exData5",objectiveGuid);
					obj.put("exData6",objectiveGuid);
					arr.add(obj);
				}
				JSONObject objtwo = new JSONObject();
				objtwo.put("batchId", id);
				objtwo.put("total", ListNum2);
				objtwo.put("data", arr);

				long time=System.currentTimeMillis();
				def reJson = HttpClientProxy.sendPost(httpURL, objtwo.toString(),proxyIp,proxyPort);
				JSONObject json = new JSONObject().fromObject(reJson);
				long etime=System.currentTimeMillis();

				String code=json.code;
				StringBuffer sql = new StringBuffer("insert into list_push_history ");
				sql.append("(id,batch_id,customer_guid,is_flag,activity_name,custlist,");
				sql.append("createddate,mobile,tel_1,atel_1,atel_2,atel_3,atel_4,customer_name,send_type,in_enddate,objective_guid) ");
				sql.append("select sys_guid(),id,customer_guid,'"+code+"',activity_name,custlist,");
				sql.append("sysdate,mobile,tel_1,atel_1,atel_2,atel_3,atel_4,customer_name,send_type,in_enddate,objective_guid ");
				sql.append("from list_push_temporary where is_push='1' and send_type='2'");
				int row7=eliteBean.update(sql.toString(),"dataSource");
				log.debug("本次推送记录至历史表数量:"+row7);

				if(json.code == "0") {
					def deleteSQL1="delete from list_push_temporary where is_push='1' and send_type='2'"
					int row8=eliteBean.update(deleteSQL1,"dataSource");
					log.debug("本次推送清除临时表数量:"+row8);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String sendHttpPost(String url, String JSONBody, String pIP, int pPort) throws Exception {
		CloseableHttpClient httpclient = null;
		HttpHost proxy=null;
		if (pIP == null || pIP.length() <= 0) {
			httpclient = HttpClients.createDefault();
		} else {
			// 设置代理IP、端口、协议（请分别替换）
			proxy = new HttpHost(pIP, pPort, "http");
		}
		// 把代理设置到请求配置
		//RequestConfig reqConfig = RequestConfig.custom().setProxy(proxy).setSocketTimeout(50000).setConnectTimeout(50000).setConnectionRequestTimeout(50000).build();
		RequestConfig reqConfig = RequestConfig.custom().setProxy(proxy).build();

		// 实例化CloseableHttpClient对象
		httpclient = HttpClients.custom().setDefaultRequestConfig(reqConfig).build();

		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-Type", "application/json");
		httpPost.setEntity(new StringEntity(JSONBody));
		CloseableHttpResponse response = httpclient.execute(httpPost);
		HttpEntity entity = response.getEntity();
		String responseContent = EntityUtils.toString(entity, "UTF-8");
		response.close();
		httpclient.close();
		return responseContent;
	}


	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
			//log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
				//log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
			} catch (Exception e1) {
				Rev_Value = "";
				//log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				//log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
				Rev_Value = "";
			}
		}
		return Rev_Value;
	}
	/**
	 * 以逗号分割加单引号
	 * @param str
	 * @return
	 */
	public static String spilt(String str) {
		StringBuffer sb = new StringBuffer();
		String[] temp = str.split(",");
		for (int i = 0; i < temp.length; i++) {
			if (!"".equals(temp[i]) && temp[i] != null)
				sb.append("'" + temp[i] + "',");
		}
		String result = sb.toString();
		String tp = result.substring(result.length() - 1, result.length());
		if (",".equals(tp))
			return result.substring(0, result.length() - 1);
		else
			return result;
	}
	/**
	 * 获取where in语句
	 *
	 * @param column      字段名
	 * @param values      值集合
	 * @return where in语句
	 */
	public static String GetWhereInValuesSql(String column, List<String> values) {
		// sql语句
		String sql = "(";
		// 值的个数
		int valueSize = values.size();
		log.debug("值的个数："+valueSize);
		// 批次数
		int batchSize = valueSize / 1000 + (valueSize % 1000 == 0 ? 0 : 1);
		for (int i = 0; i < batchSize; i++) {
			if (i > 0) {
				sql += ") or ";
			}
			sql += column+" in (";
			for (int j = i * 1000; ( j < (i + 1) * 1000) && j < valueSize; j++) {
				if (j > i * 1000) {
					sql += ",";
				}
				sql += "'" + values.get(j) + "'";
			}
		}
		sql += "))";
		return sql;
	}
}